package com.googlecode.frameworksintegration.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.googlecode.frameworksintegration.domain.Blog;
/**
 * Struts 2 Integrated with Hibernate 3 blogging example.
 * http://java.searchdaily.net
 * @author namnvhue
 * 
 */
public class BlogDAOImpl implements BlogDAO {
	private EntityManagerFactory entityManagerFactory;
	private EntityManager entityManager;

	public BlogDAOImpl() {
		this.entityManagerFactory = Persistence
				.createEntityManagerFactory("blogds");
		this.entityManager = entityManagerFactory.createEntityManager();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Blog> listBlogs() {
		Query q = entityManager.createQuery("select blog from Blog blog");
		return q.getResultList();

	}

	@Override
	public void save(Blog blog) {
		entityManager.getTransaction().begin();
		entityManager.persist(blog);
		entityManager.flush();
		entityManager.getTransaction().commit();
	}

	@Override
	public void delete(Blog blog) {
		entityManager.getTransaction().begin();
		entityManager.remove(blog);
		entityManager.flush();
		entityManager.getTransaction().commit();
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

	@Override
	public Blog find(Integer id) {
		return entityManager.find(Blog.class, id);

	}

}
